<?php

class Weather
{

    private $_dbFile;

    public function __construct($dbFile=null)
    {
        if (!is_null($dbFile) and is_file($dbFile)) {
            $this->_dbFile = $dbFile;
        }
    }

    /**
     * 获取城市信息
     * 
     * @param  str $cityCode [description]
     * 
     * @return array
     */
    private function _getWeatherInfo ($cityCode)
    {
        // api 链接
        $url= "http://m.weather.com.cn/data/".$cityCode.".html";

        $ch = curl_init();
        $timeout = 10;

        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        $weatherInfo = curl_exec($ch);
        curl_close($ch);

        return json_decode($weatherInfo, true);
    }

    public function getWeatherInfo()
    {
        header("Content-Type: text/html; charset=UTF-8");
        $city = $_POST['city'];
        $cityDb = $this->_getCityDb();

        if(array_key_exists($city, $cityDb)){
            echo json_encode($this->_getWeatherInfo($cityDb[$city]));
        }else{
            echo '{"error_response": "您输入的城市不正确"}';
        }
    }

    private function _getCityDb()
    {
        return include $this->_dbFile;
    }
}

$webO = new Weather('./cityDb.php');
$webO->getWeatherInfo();
